class Membership < ActiveRecord::Base
  belongs_to :user, :counter_cache => :projects_count
  belongs_to :project, :counter_cache => :members_count

  validates_uniqueness_of :user_id, :scope => :project_id

  # creates a membership for user, project
  def self.join( project, user )
    if m = find( :first, :conditions =>
        ['user_id = ? AND project_id = ?', user.id, project.id] )
      m
    else
      create( :user => user, :project => project )
    end
  end

  # removes a membership for user, project
  def self.leave( project, user )
    if m = find( :first, :conditions =>
        ['user_id = ? AND project_id = ?', user.id, project.id] )
      m.destroy
    end
  end

  # returns whether user is a member of project
  def self.member?( project, user )
    ( find( :first, :conditions =>
        ['user_id = ? AND project_id = ?', user.id, project.id] ) ?
      true : false )
  end

  def inspect
    "Membership( #{project.name}, #{user.display} )"
  end
end
